<template>
	<div class="pdf-container">
		<div class="pdf-controls" v-if="pdfDoc">
			<button @click="prevPage" :disabled="pageNum <= 1">上一页</button>
			<span>{{ pageNum }} / {{ numPages }}</span>
			<button @click="nextPage" :disabled="pageNum >= numPages">下一页</button>
			<button @click="zoomIn">放大</button>
			<button @click="zoomOut">缩小</button>
			
		</div>
		<div class="loading" v-if="!pdfDoc && !error">加载中...</div>
		<div class="error" v-if="error">{{ error }}</div>
		<canvas ref="pdfCanvas"></canvas>
	</div>
</template>

<script>
// 使用CDN版本的pdf.js，避免npm包的编译问题
// import * as pdfjsLib from 'pdfjs-dist';

export default {
	name: 'PdfViewer',
	props: {
		pdfUrl: {
			type: String,
			required: true
		}
	},
	data() {
		return {
			pdfDoc: null,
			pageNum: 1,
			numPages: 0,
			pageRendering: false,
			pageNumPending: null,
			// scale: 1.5,
			scale: 2.25,
			error: null,
			pdfjsLib: null
		};
	},
	watch: {
		pdfUrl: {
			handler(newUrl) {
				if (newUrl) {
					this.$nextTick(() => {
						this.loadPdf();
					});
				}
			},
			immediate: true
		}
	},
	async mounted() {
		// 动态加载CDN版本的pdf.js
		await this.loadPdfJS();
	},
	methods: {
		async loadPdfJS() {
			try {
				// 检查是否已经加载
				if (window.pdfjsLib) {
					this.pdfjsLib = window.pdfjsLib;
					return;
				}

				// 动态加载pdf.js脚本
				const script = document.createElement('script');
				script.src = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.6.347/pdf.min.js';
				script.onload = () => {
					this.pdfjsLib = window.pdfjsLib;
					// 设置worker路径
					this.pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.6.347/pdf.worker.min.js';
					// 如果已经有URL，则加载PDF
					if (this.pdfUrl) {
						this.loadPdf();
					}
				};
				script.onerror = () => {
					this.error = '无法加载PDF.js库';
				};
				document.head.appendChild(script);
			} catch (error) {
				console.error('加载PDF.js库失败:', error);
				this.error = '无法加载PDF.js库';
			}
		},
		loadPdf() {
			if (!this.pdfjsLib) {
				// 如果库还没加载完成，等待加载
				setTimeout(() => this.loadPdf(), 100);
				return;
			}

			this.error = null;
			this.pdfDoc = null;

			// 设置CORS模式和缓存控制
			const loadingTask = this.pdfjsLib.getDocument({
				url: this.pdfUrl,
				withCredentials: false,
				cMapUrl: 'https://cdn.jsdelivr.net/npm/pdfjs-dist@2.6.347/cmaps/',
				// cMapPacked: true
				cMapPacked: false
			});

			loadingTask.promise
				.then((pdfDoc) => {
					this.pdfDoc = pdfDoc;
					this.numPages = pdfDoc.numPages;
					this.$nextTick(() => {
						this.renderPage(this.pageNum);
					});
				})
				.catch((error) => {
					console.error('加载PDF出错:', error);
					// 提供更详细的错误信息
					if (error.name === 'MissingPDFException') {
						this.error = '无法找到PDF文件，请检查URL是否正确';
					} else if (error.name === 'InvalidPDFException') {
						this.error = 'PDF文件无效或已损坏';
					} else if (error.name === 'UnexpectedResponseException') {
						this.error = '服务器返回了意外的响应，可能是跨域问题';
					} else if (error.message && error.message.includes('Failed to fetch')) {
						this.error = 'PDF文件获取失败，可能是网络问题或跨域限制';
					} else {
						this.error = `加载PDF出错: ${error.message || '未知错误'}`;
					}
				});
		},
		renderPage(num) {
			if (!this.pdfDoc) return;

			this.pageRendering = true;
			this.pdfDoc
				.getPage(num)
				.then((page) => {
					const viewport = page.getViewport({ scale: this.scale });
					const canvas = this.$refs.pdfCanvas;
					const ctx = canvas.getContext('2d');

					canvas.height = viewport.height;
					canvas.width = viewport.width;

					const renderContext = {
						canvasContext: ctx,
						viewport: viewport
					};

					page.render(renderContext).promise.then(() => {
						this.pageRendering = false;
						if (this.pageNumPending !== null) {
							this.renderPage(this.pageNumPending);
							this.pageNumPending = null;
						}
					});
				})
				.catch((error) => {
					console.error('渲染PDF页面出错:', error);
					this.error = `渲染PDF页面出错: ${error.message}`;
					this.pageRendering = false;
				});
		},
		queueRenderPage(num) {
			if (this.pageRendering) {
				this.pageNumPending = num;
			} else {
				this.renderPage(num);
			}
		},
		prevPage() {
			if (this.pageNum <= 1) return;
			this.pageNum--;
			this.queueRenderPage(this.pageNum);
		},
		nextPage() {
			if (this.pageNum >= this.numPages) return;
			this.pageNum++;
			this.queueRenderPage(this.pageNum);
		},
		zoomIn() {
			this.scale += 0.25;
			this.queueRenderPage(this.pageNum);
		},
		zoomOut() {
			if (this.scale <= 0.5) return;
			this.scale -= 0.25;
			this.queueRenderPage(this.pageNum);
		}
	}
};
</script>

<style lang="less" scoped>
.pdf-container {
	width: 100%;
	overflow: auto;
	display: flex;
	flex-direction: column;
	align-items: center;
}

.pdf-controls {
	margin-bottom: 10px;
	display: flex;
	gap: 10px;
	align-items: center;
}

.pdf-controls button {
	padding: 5px 10px;
	background-color: #4caf50;
	color: white;
	border: none;
	border-radius: 4px;
	cursor: pointer;
}

.pdf-controls button:disabled {
	background-color: #cccccc;
	cursor: not-allowed;
}

.loading,
.error {
	padding: 20px;
	text-align: center;
}

.error {
	color: red;
}

canvas {
	border: 1px solid #ddd;
	max-width: 100%;
}
</style>
